const axios = require('axios')
const randomstring = require('randomstring')
const querystring = require('querystring')
const crypto = require('crypto')

const signature = async (ctx, next) => {
  const APPID = 'wx7ba8ee8a8beace33'
  const APPSECRET = 'd62705bd6fdf27441397683019077e20'

  let { access_token } = (await axios.get(`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${APPID}&secret=${APPSECRET}`)).data

  let { ticket: jsapi_ticket} = (await axios.get(`https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${access_token}&type=jsapi`)).data

  const noncestr = randomstring.generate(32)
  const timestamp = new Date().getTime()
  const url = 'https://walter666.cn/jssdk.html'

  const signObj = {
    timestamp,
    jsapi_ticket,
    noncestr,
    url
  }
  const orderedSignObj = Object.keys(signObj).sort().reduce((obj, key) => {
    obj[key] = signObj[key]
    return obj
  }, {})
  const string1 = querystring.stringify(orderedSignObj, null, null, {
    encodeURIComponent: (str) => {
      return querystring.unescape(str)
    }
  })
  const signature = crypto.createHash('sha1').update(string1).digest('hex')
  
  ctx.body = {
    appId: APPID,
    nonceStr: noncestr,
    timestamp,
    signature
  }
}

module.exports = {
  signature
}